package com.dj.ms.support.log;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.openservices.log.Client;
import com.aliyun.openservices.log.common.LogItem;
import com.aliyun.openservices.log.exception.LogException;
import com.aliyun.openservices.log.request.PutLogsRequest;
import com.aliyun.openservices.log.response.PutLogsResponse;
import com.dj.ms.configure.AliYunLogClientConfiguration;
import com.dj.ms.event.AsyncNoTaskListener;
import com.google.common.collect.Lists;
import com.google.common.eventbus.Subscribe;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.*;


/**
 * <br>
 * <p>
 *     日志记录监听器
 * </p>
 * <br>
 * @author ZJG
 * @version 1.0
 * @date 2021/9/27 下午7:01
 */
@Slf4j
@Component
public class OperateLogListener implements AsyncNoTaskListener {

    private Client client;

    @Subscribe
    public void processOrderCancelEvent(OperateLogPutEvent event) {
        if (Objects.isNull(event) || Objects.isNull(event.getLogMetadata())) {
            return;
        }
        pushLog(event.getLogMetadata());
    }

    @Async
    public void pushLog(OperateLogMetadata logMetadata) {
        if (Objects.isNull(client)) {
            client = AliYunLogClientConfiguration.aliyunLogStoreClient();
        }
        try {
            Map<String, Object> adminLogMap = BeanUtil.beanToMap(logMetadata);
            List<LogItem> logItems = Lists.newArrayList();
            LogItem logItem = new LogItem();
            adminLogMap.keySet()
                    .stream()
                    .forEach(key -> logItem.PushBack(key, Objects.toString(adminLogMap.get(key), "")));

            logItems.add(logItem);
            PutLogsRequest putLogsRequest = new PutLogsRequest(
                    AliYunLogClientConfiguration.projectName,
                    AliYunLogClientConfiguration.logStore,
                    AliYunLogClientConfiguration.topic,
                    logMetadata.getOperationIp(),
                    logItems);

            PutLogsResponse response = client.PutLogs(putLogsRequest);
            if (Objects.nonNull(response)) {
                log.info("log push log store success. response::{}", JSONObject.toJSONString(response));
            }
        } catch (LogException e) {
            log.warn("log push log store fail. ex::{}", e);
        }
    }

}
